import React, { useEffect, useState } from "react";
import {
  Card,
  Button,
  Table,
  Image,
  Modal,
  Form,
  Input,
  Popconfirm,
} from "antd";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import trademarkApi from "@/api/trademark";
import { TrademarkListData, TrademarkData } from "@/api/trademark";
import { message, Upload } from "antd";
import type { UploadChangeParam } from "antd/es/upload";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import { useForm } from "antd/lib/form/Form";
import { RcFile } from "antd/lib/upload";

export default function Trademark() {
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      dataIndex: "id",
      align: "center",
      width: 80,
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      // dataIndex: "logoUrl",开始留空,渲染后将dataIndex改为对应数据字段
      render: (row: TrademarkData) => {
        return <Image src={row.logoUrl} width={80} alt={row.tmName}></Image>;
      },
    },
    {
      title: "操作",
      fixed: "right",
      render: (x: any, row: TrademarkData, index: number) => {
        return (
          <>
            <Button
              onClick={() => {
                showUpdateModal(row);
              }}
              icon={<EditOutlined />}
              style={{
                marginRight: 10,
                backgroundColor: "#e6a23c",
                color: "white",
              }}
            >
              修改
            </Button>
            <Popconfirm
              title={`你确定要删除${row.tmName}吗`}
              onConfirm={() => {
                deleteTrademark(row);
              }}
              onCancel={cancel}
              okText="确定"
              cancelText="取消"
            >
              <Button
                style={{
                  backgroundColor: "#f56c6c",
                  color: "white",
                }}
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  //定义trademarkList数据
  const [trademarkList, setTrademarkList] = useState<TrademarkListData>([]);
  //定义分页数据
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(3);
  const [total, setTotal] = useState(10);
  const [tmInfo, setTmInfo] = useState<TrademarkData>({
    tmName: "",
    logoUrl: "",
  });

  //  定义对话框数据
  const [isModalOpen, setIsModalOpen] = useState(false);

  //Form表单数据
  let [form] = useForm();

  //显示对话框
  const showModal = () => {
    setIsModalOpen(true);
    form.resetFields();
    setImageUrl("");
    setTmInfo({
      //重置品牌名称和图片地址
      tmName: "",
      logoUrl: "",
    });
  };

  // input框改变时的回调,收集tmName
  const inputChange = (e: any) => {
    let tmName = e.target.value;
    setTmInfo({ ...tmInfo, tmName });
  };

  // 点击添加或修改的请求函数
  const addorUpdate = async () => {
    try {
      // console.log(tmInfo);
      await trademarkApi.addOrUpdateTrademark(tmInfo);
      message.success(tmInfo.id ? "修改品牌成功" : "添加品牌成功");
      if (tmInfo.id) {
        getTrademarkList(current);
      } else {
        setCurrent(1);
        getTrademarkList();
      }
    } catch (error) {
      message.error(tmInfo.id ? "修改品牌失败" : "添加品牌失败");
    }
  };

  // 删除trademark
  const deleteTrademark = async (row: TrademarkData) => {
    try {
      await trademarkApi.removeTrademark(row.id as number);
      message.success("删除品牌成功");
      getTrademarkList(trademarkList.length > 1 ? current : current - 1);
    } catch (error) {
      message.error("删除品牌失败");
    }
  };

  const cancel = () => {
    message.error("取消删除");
  };

  //点击确定的回调,发请求(添加/删除)
  const handleOk = async () => {
    // 表单验证
    try {
      await form.validateFields(["tmName", "logoUrl"]);
      addorUpdate();
      setIsModalOpen(false);
    } catch (error) {
      message.error("校验失败");
    }
  };

  //点击取消的回调
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 点击修改回显数据
  const showUpdateModal = (row: TrademarkData) => {
    setIsModalOpen(true);
    // console.log(row.tmName);
    form.setFieldsValue(row);
    setImageUrl(row.logoUrl);
    setTmInfo({ ...row });
  };

  // 上传头像区域
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setLoading(false);
      setImageUrl(info.file.response.data);
      let logoUrl = info.file.response.data;
      setTmInfo({ ...tmInfo, logoUrl }); //收集logoUrl
    }
  };

  //图片上传的地址
  const baseUrl = process.env.REACT_APP_API;

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("图片只能为jpg或png格式!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片不能大于2M");
    }
    return isJpgOrPng && isLt2M;
  };

  //定义一个函数,用于获取trademarkList列表
  const getTrademarkList = async (page = current, limit = pageSize) => {
    try {
      let result = await trademarkApi.reqTrademarkList(page, limit);
      // console.log(result);
      setTrademarkList(result.records);
      // 设置分页的总数
      setTotal(result.total);
    } catch (error) {}
  };

  useEffect(() => {
    getTrademarkList();
  }, [current, pageSize]);

  return (
    <Card>
      <Button
        onClick={showModal}
        type="primary"
        icon={<PlusOutlined />}
        style={{ marginBottom: 20 }}
      >
        添加
      </Button>
      <Modal
        title="添加品牌"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form}>
          <Form.Item
            label="品牌名称"
            name="tmName"
            rules={[
              { required: true, message: "品牌名称必填" },
              {
                min: 2,
                max: 10,
                message: "品牌名称长度2-10",
              },
            ]}
          >
            <Input
              name="tmName"
              onChange={(e) => {
                inputChange(e);
              }}
            ></Input>
          </Form.Item>
          <Form.Item
            label="品牌LOGO"
            name="logoUrl"
            valuePropName="logoUrl"
            rules={[{ required: true, message: "品牌LOGO必须上传" }]}
          >
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action={`${baseUrl}/admin/product/upload`}
              onChange={handleChange}
              beforeUpload={beforeUpload}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Table
        rowKey="id"
        style={{ marginBottom: 20 }}
        dataSource={trademarkList}
        columns={columns}
        bordered
        pagination={{
          total: total, //总条数
          pageSize: pageSize, //每页显示的数量
          current: current, //当前页码
          showQuickJumper: true, //是否显示快速跳转组件
          pageSizeOptions: [2, 5, 10, 15], //调整每页显示的数量 数组
          showSizeChanger: true,
          showTotal: (total) => {
            return <span>总计{total}条</span>;
          },
          onChange: (current: number, pageSize: number) => {
            setCurrent(current);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
